# 用于返回上一级或多级目录
# 如果没有参数则返回上一级
# 如果有一个参数，且为数字,向上返回N级
# 如果参数为[f|F]C 表示像后或向前搜索以C开头的目录
function cb

# 防止根目录在字符串操作中被替代，先用一个fakeroot替代，之后在换回来
set p "fakeroot"(pwd)
set index 1
if [ -z $argv ]
    cd ..
    return
end

# 显示帮助信息
if [ $argv[1] = "-h" ]
    cbhelp
    return
end
# 处理当前目录
# 使用fish 里面的string命令将当前目录分割

set parsedlist (string split "/" $p)
set target ""
# 按深度定位
set step (echo $argv[1] | grep '^[0-9]$')
if [ 0 -eq $status ]
    # 如果参数是数字，代表向上以及目录跳转
    set step (expr -$step - 1)
    set target $parsedlist[1..$step]
    set targetpath (string join "/" $target)
    set targetpath (string replace "fakeroot" "/" $targetpath)
    cd $targetpath
    return
end

# 按字母定位
set index 0
set mode (echo $argv[1] | grep -o "^[fF]")
if [ -z "$mode" ]
    echo "invalid"
    cbhelp
    return
end
set key (echo $argv[1] | grep -Po "(?<=^[fF]).")

if [ $mode = "f" ]
    # 从左到右搜索
    for i in (seq 2 (count $parsedlist))
        string match -q -r "^$key" $parsedlist[$i]
        if [ $status -eq 0 ]
            set index $i
            break
        end
        # 如果没有找到，不改变
        if [ $i -eq (count $parsedlist) ]
            set index (count $parsedlist)
        end
    end

else
    for i in (seq (count $parsedlist) -1 1)
        string match -q -r "^$key" $parsedlist[$i]
        if [ $status -eq 0 ]
            set index $i
            break
        end
        if [ $i -eq 1 ]
            set index (count $parsedlist)
        end
    end
end
set target (string join "/" $parsedlist[1..$index])
set target (string replace "fakeroot" "/" $target)
cd $target
# end of function
end

# short help message
function cbhelp
echo -e "usage: cb [ \033[32mback-level\033[0m ] | [\033[31mf\033[0m|\033[31mF\033[0m]\033[32mC\033[0m "
echo -e "       \033[31mf\033[0m|\033[31mF\033[0m followed by a Character \033[32mC\033[0m means \
you want to search for the dir starting with \033[32mC\033[0m forwards/backwards"
end
